﻿using System;
using System.Configuration;
using System.Data;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Threading;
using WHC.OrderWater.Commons;
using WHC.Hotel.Entity;
using WHC.Hotel.BLL;


namespace WHC.Hotel.UI
{

    public delegate void ProgressHandle(string msg);
    public  class AuditService
    {
        private Thread workThread = null;
        private bool _isRunning = false;//是否在运行
        private bool _shouldStop = false;//线程是否要停止
        public event ProgressHandle ProgressHandleEvent;
        private DateTime nextAuditDateTime = Convert.ToDateTime(ConfigurationManager.AppSettings["NextAuditDate"].ToString() + " " + ConfigurationManager.AppSettings["NextAuditTime"].ToString());
        /// <summary>
        ///是否在运行 
        /// </summary>
        public bool IsRunning
        {
            get { return _isRunning; }
            set { _isRunning = value; }
        }

        /// <summary>
        /// 出发事件
        /// </summary>
        /// <param name="msg"></param>
        private void OnActionEvent(string msg)
        {
            if (ProgressHandleEvent != null)
            {

                ProgressHandleEvent(msg);
            }


        }
        /// <summary>
        /// 启动设备故障通知服务
        /// </summary>
        public void start()
        {


            try
            {


                workThread = new Thread(new ThreadStart(Execute));
                workThread.IsBackground = true;
                workThread.Start();
                LogHelper.Info("夜审服务启动");
                OnActionEvent("夜审服务启动");


            }
            catch (Exception ex)
            {

                // LogHelper.WriteException("命令下发中转服务启动出现异常",ex);
                LogHelper.Info("夜审服务启动出现异常",ex);
                OnActionEvent("夜审服务启动出现异常");


            }



        }

        /// <summary>
        /// 执行设备状态恢复处理
        /// </summary>
        private void Execute()
        {
            DataTable dt = null;
            int iCount = 0;
            string alertMsg = string.Empty;
            while (!_isRunning && (!_shouldStop)&& DateTime.Now>nextAuditDateTime)
            {
                _isRunning = true;

                try
                {

                    LogHelper.Info("开始" + nextAuditDateTime.Date.ToString("yyyy-MM-dd") + "夜审工作");
                    dt = BLLFactory<Order>.Instance.FindToDataTable(" IsVirtualAccount=0 and  IsCheckOut=0 and  IsPartTime=0 ");
                 
                    if (dt != null &&dt.Rows.Count > 0)
                    {
                        iCount = dt.Rows.Count;
                        for (int i = 0; i < iCount; i++)
                        {

                            //判断是否已经存在当天夜审记录
                            if (!BLLFactory<ConsumerList>.Instance.IsExistRecord("  Order_ID=" + Convert.ToInt32(dt.Rows[i]["ID"].ToString()) + " and  RoomNo='" + dt.Rows[i]["RoomNo"].ToString() + "' and   BeginTime>='" + nextAuditDateTime.Date.ToString("yyyy-MM-dd") + "' and    BeginTime<='" + nextAuditDateTime.Date.ToString("yyyy-MM-dd") + " 23:59:00'"))
                            {

                                ConsumerListInfo info = new ConsumerListInfo();
                                info.Amount = Convert.ToDecimal(dt.Rows[i]["DiscountPrice"].ToString());
                                info.BeginTime = nextAuditDateTime.Date;
                                info.Creator = Portal.gc.LoginInfo.FullName;
                                info.Discount = Convert.ToDouble(dt.Rows[i]["DiscountRate"].ToString());
                                info.DiscountPrice = Convert.ToDecimal(dt.Rows[i]["DiscountPrice"].ToString());
                                info.EndTime = nextAuditDateTime.Date;
                                info.ItemNo = "001";
                                info.ItemName = "夜房费";
                                info.ItemType = "夜房费";
                                info.Order_ID = Convert.ToInt32(dt.Rows[i]["ID"].ToString()); ;
                                info.Price = Convert.ToDecimal(dt.Rows[i]["OriginalPrice"].ToString());
                                info.Quantity = 1;
                                info.RoomNo = dt.Rows[i]["RoomNo"].ToString();
                                info.Waiter = "*";
                                if (dt.Rows[i]["BillNumber"].ToString().IndexOf('_') > -1)
                                {
                                    info.Account =dt.Rows[i]["BillNumber"].ToString().Substring(0,dt.Rows[i]["BillNumber"].ToString().IndexOf('_'));
                                }
                                else
                                {
                                    info.Account = dt.Rows[i]["BillNumber"].ToString();

                                }
                                BLLFactory<ConsumerList>.Instance.Insert(info);
                                BLLFactory<Order>.Instance.UpdateAuditStatus(info.Order_ID, info.BeginTime);
                                LogHelper.Info("房间号" + dt.Rows[i]["RoomNo"].ToString() + "过房费到主账单(" + info.Account + ")成功");

                            }





                        }

                        SetValue("NextAuditDate",nextAuditDateTime.Date.AddDays(1).ToString("yyyy-MM-dd"));




                    }
                  

                    LogHelper.Info(""+nextAuditDateTime.Date.ToString("yyyy-MM-dd")+"夜审工作完成");
                    OnActionEvent(alertMsg);


                }
                catch (Exception ex)
                {

                    LogHelper.Info("夜审出现异常", ex);
                    OnActionEvent("夜审处理出现异常");


                }
                finally
                {

                    _isRunning = false;


                }

                nextAuditDateTime = Convert.ToDateTime(ConfigurationManager.AppSettings["NextAuditDate"].ToString() + " " + ConfigurationManager.AppSettings["NextAuditTime"].ToString());
                //休眠5分钟
                Thread.Sleep(10*601000);


            }



        }

        /// <summary>
        /// 停止线程
        /// </summary>
        public void Stop()
        {
            _shouldStop = true;
            Thread.Sleep(100);
            LogHelper.Info("停止自动夜审服务");
            OnActionEvent("停止自动夜审服务");
            if (workThread != null && workThread.ThreadState == ThreadState.Running)
            {

                workThread.Abort();
            }
            LogHelper.Info("停止自动夜审服务成功");
            OnActionEvent("停止自动夜审服务成功");

        }


        ///   <summary>   
        ///   向.config文件的appKey结写入信息AppValue   保存设置   
        ///   </summary>   
        ///   <param   name="AppKey">节点名</param>   
        ///   <param   name="AppValue">值</param>
        private  void SetValue(String AppKey,String AppValue)
        {  
            
            XmlDocument xDoc=new XmlDocument();
            xDoc.Load(System.Windows.Forms.Application.ExecutablePath+".config");
            XmlNode xNode;
            XmlElement xElem1;
            xNode=xDoc.SelectSingleNode("//appSettings");
            xElem1=(XmlElement)xNode.SelectSingleNode("//add[@key='"+AppKey+"']");
            if(xElem1!=null)
            xElem1.SetAttribute("value",AppValue);
            xDoc.Save(System.Windows.Forms.Application.ExecutablePath+".config");
           
        
          }
    
    
    
    }
}
